<template>
  <div class="modify-dialog">
    <slot>
      <el-upload
        id="saleUploader"
        ref="uploader"
        accept=".xls,.xlsx"
        style="display: inline-block"
        :headers="headers"
        :action="`${$apiHost}/sale/saleExport`"
        :on-success="onSuccess"
        :show-file-list="false"
      >
        <el-button size="small" type="primary"> 导入报货单 </el-button>
      </el-upload>
    </slot>
    <el-dialog v-bind="dialogOpts" :visible.sync="dialogVisible">
      <Form v-bind="formOpts" v-on="formEvent">
        <template #formSuf v-if="modify != 'edit'">
          <el-form-item label="材料" style="width: 100%">
            <div class="prod-wrap" :style="{ maxHeight: '45vh' }">
              <div v-for="(e, i) in saleMaterials" :key="e.key">
                <el-collapse v-model="activeNames">
                  <el-collapse-item :name="e.key">
                    <template slot="title">
                      <div class="norms materialName">
                        <div class="content">
                          {{ e.materialName }}
                        </div>
                      </div>
                      <div class="norms" style="min-width: 100px">
                        {{ e.unit }}
                      </div>
                      <div class="norms" style="min-width: 140px">
                        {{ e.norm }}
                      </div>
                      <div
                        class="norms"
                        style="flex: 1; margin-right: 30px; text-align: right"
                      >
                        数量：{{ e.count }}
                      </div>
                    </template>
                    <div>
                      <div class="tips">
                        注意：所有自定义材料数量之和需等于{{ e.count }}
                      </div>
                      <div
                        style="margin-bottom: 20px"
                        v-for="(_e, _i) in e.items"
                        :key="_e.id + _i"
                      >
                        <el-select
                          v-model="_e.id"
                          placeholder="请选择"
                          style="width: 180px"
                        >
                          <el-option
                            v-for="item in e.colors"
                            :disabled="
                              e.items.some((v) => v.id == item.materialId)
                            "
                            :key="item.materialId"
                            :label="item.color"
                            :value="item.materialId"
                          >
                          </el-option>
                        </el-select>
                        <el-input-number
                          style="margin: 0 20px"
                          v-model="_e.count"
                          :min="0"
                        ></el-input-number>
                        <span
                          v-show="e.items.length > 1"
                          class="el-icon-delete"
                          style="cursor: pointer"
                          @click="remove(i, _i)"
                        ></span>
                      </div>
                      <el-button
                        v-show="e.items.length < e.colors.length"
                        size="mini"
                        @click="add(i)"
                      >
                        新增材料
                      </el-button>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-form-item>
        </template>
        <template #formBtn>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onConfirm"> 确 定 </el-button>
          </div>
        </template>
      </Form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { mapGetters } from "vuex";
import ProductInput from "./ProductInput.vue";
import modifyMixins from "@/mixins/modifyMixins.vue";
export default {
  mixins: [modifyMixins],
  components: {
    ProductInput,
  },
  data() {
    return {
      dialogWidth: "70vw",
      saleMaterials: [],
      activeNames: [],
      modifyType: "",
      modifyRow: {},
      form: {
        orderName: {
          tag: "el-input",
          label: "订单名称",
          value: "",
          props: {
            clearable: true,
            filterable: true,
            placeholder: "请输入订单名称",
          },
        },
        storeName: {
          tag: "el-input",
          label: "门店名称",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入门店名称",
          },
        },
        storeContacts: {
          tag: "el-input",
          label: "门店联系方式",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入门店联系方式",
          },
        },
        storeAddress: {
          tag: "el-input",
          label: "门店地址",
          value: "",
          props: {
            rows: 3,
            type: "textarea",
            clearable: true,
            placeholder: "请输入门店地址",
          },
        },
        receivedAmount: {
          tag: "el-input-number",
          label: "回款金额",
          value: "",
          props: {
            min: 0,
            precision: 2,
            clearable: true,
            placeholder: "请输入回款金额",
          },
        },
        paymentVouchers: {
          tag: "Uploader",
          label: "回款凭证",
          value: [],
          props: {},
        },
        warehouseId: {
          tag: "el-select",
          label: "仓库",
          value: "",
          items: [],
          props: {
            clearable: true,
            filterable: true,
          },
        },
        remark: {
          tag: "el-input",
          label: "备注",
          value: "",
          props: {
            rows: 3,
            type: "textarea",
            clearable: true,
            placeholder: "请输入备注",
          },
        },
      },
    };
  },
  computed: {
    ...mapState(["tokenv3"]),
    headers() {
      return {
        token: this.tokenv3 || window.$quinn.getStorage("tokenv3"),
      };
    },
  },
  watch: {},
  mounted() {},
  methods: {
    onSuccess(res) {
      if (res.code == 200 && res.data) {
        const data = res.data;
        this.saleMaterials = (data?.materials || []).map((e) => {
          e.items = e?.colors
            ?.slice(0, 1)
            .map((v) => ({ count: e.count, id: v.materialId }));
          e.key = this.$quinn.guid();
          return e;
        });
        // this.activeNames = this.saleMaterials.map((e) => e.key);
        this.showDialog(this.modifyType || "add", data);
      }
    },
    add(i) {
      this.saleMaterials = this.saleMaterials.map((item, index) => {
        if (index == i) item.items.push({ count: 0, id: "" });
        return item;
      });
    },
    remove(i, _i) {
      this.saleMaterials = this.saleMaterials.map((item, index) => {
        if (index == i) item.items = item.items.filter((e, ind) => ind != _i);
        return item;
      });
    },
    showDialog(modify = "add", row = {}) {
      this.dialogVisible = true;
      this.row = { ...this.modifyRow, ...row };
      this.modify = this.modifyType || modify || "add";
      this.modifyType = "";
      this.modifyRow = {};
      this.form.warehouseId.items = this.$store.getters.warehouseListItems;
      for (const key in this.form) {
        let defValue = "";
        if (Array.isArray(this.form[key].value)) defValue = [];
        if (Object.hasOwnProperty.call(row, key))
          this.form[key].value = row[key];
        else this.form[key].value = defValue;
        if (["import"].includes(this.modify)) this.form[key].hidden = true;
        else this.form[key].hidden = false;
      }
      this.formKey = this.$quinn.guid();
    },
    onSubmit(form) {
      const { modify, row } = this;
      if (
        modify != "edit" &&
        this.saleMaterials.some((item) => {
          let total = 0;
          item.items.forEach((e) => (total += e.count));
          return item.count != total;
        })
      )
        return this.$message.error("数量有误请检查");
      form.materials = this.saleMaterials.reduce((a, b) => {
        return [].concat(
          a,
          b.items.filter((e) => e.count && e.id)
        );
      }, []);
      if (modify === "add") {
        form.paymentVouchers = form.paymentVouchers.join(",");
        this.$api["saleSaleAdd"](form).then(this.submitDoneMsg);
      } else if (["import"].includes(modify))
        this.$api
          .saleSaleRepeatAdd({ ...form, saleId: row.saleId })
          .then(this.submitDoneMsg);
      else if (["edit"].includes(modify))
        this.$api
          .supplierSupplierUpdate({ ...form, saleId: row.saleId })
          .then(this.submitDoneMsg);
    },
  },
};
</script>

<style lang="less" scoped>
.prod-wrap {
  overflow-y: auto;
}

.tips {
  font-size: 12px;
  color: red;
  margin-bottom: 10px;
}

.norms {
  min-width: 100px;
  padding-left: 20px;
  line-height: 1.1em;
}

.materialName {
  width: 300px;
  height: 48px;
  display: flex;
  align-items: center;
  .content {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
